package com.zx.oa.controller;

import com.alibaba.excel.EasyExcel;
import com.zx.oa.entity.ShowStudent;
import com.zx.oa.utils.excel.StudentExcel;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@WebServlet("/excelservlet.do")
public class excelservlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SimpleDateFormat sf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取到时间，以时间来定义下载Excel的名称
        String downLoadTime=sf.format(new Date());

        List<ShowStudent> showStudentList= (List<ShowStudent>) request.getSession().getAttribute("studentListAll");
        //设置Excel响应头
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        //下载的Excel文件名称
        String fileName="Student"+downLoadTime+".xlsx";
        response.setHeader("Content-disposition","allachment;filename="+fileName);
        EasyExcel.write(response.getOutputStream(),
                StudentExcel.class).sheet("学生信息").doWrite(showStudentList);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
